package com.tcm.kafka;

import org.apache.kafka.common.serialization.Serializer;

import java.nio.ByteBuffer;
import java.util.Map;

public class CompanySerializer implements Serializer<Company> {
    @Override
    public void configure(Map<String, ?> configs, boolean isKey) {

    }

    @Override
    public byte[] serialize(String topic, Company company) {
        if(company == null){
            return null;
        }
        byte[] name, address;
        try{
            if(company.getName() != null){
                name = company.getName().getBytes();
            }else{
                name = new byte[0];
            }
            if(company.getAddress() != null){
                address = company.getAddress().getBytes();
            }else{
                address = new byte[0];
            }

            ByteBuffer buffer = ByteBuffer.allocate(4+4+name.length+address.length);
            buffer.putInt(name.length);
            buffer.put(name);
            buffer.putInt(address.length);
            buffer.put(address);
            return buffer.array();
        }catch (Exception e){
            e.printStackTrace();
        }
        return new byte[0];
    }

    @Override
    public void close() {

    }
}
